import subprocess
import time
import os
import datetime
import threading
import multiprocessing
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk

class TkBasic(tk.Tk):
    def __init__(self):
        super().__init__()
        self.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.basic_frame = tk.Frame(self, bg="#800080")
        self.basic_frame.place(relx=0, rely=0, relheight=1, relwidth=1)
        self.title("自动化任务小工具")
        # 开始语音合成入口
        self.start_text = tk.StringVar(self)
        self.start_text.set("请选择bat文件")

        x = self.winfo_screenmmwidth()
        y = self.winfo_screenheight()
        self.geometry("500x500+%d+%d" % (x, y / 2 * 0.5))
        self.resizable(0, 0)
        self.select_file_button = tk.Button(
            self.basic_frame, textvariable=self.start_text, bg="#800080",
            fg="black", command=self.select_file,
            font=("微软雅黑", 20))
        self.select_file_button.place(relx=0.3, rely=0.5, relheight=0.1, relwidth=0.5)
        # # api_key输入框
        # self.api_key = tk.Entry(self.basic_frame, textvariable=self.api_key_tips)
        # self.api_key.place_forget()

        # 提示选择按钮
        show_tips = """
            温馨提示,在选择bat文件时可以按住ctrl键\n鼠标左键点击选择多个文件.
        """
        self.info_text = tk.StringVar(self)
        self.info_text.set(show_tips)
        self.show_info_label = tk.Label(self.basic_frame, textvariable=self.info_text, bg="#800080",font=("微软雅黑", 12, "bold"))
        self.show_info_label.place(relx=0.1, rely=0.3, relheight=0.1, relwidth=0.8)
        self.next = tk.Button(self.basic_frame, text="下一步", bg="#800080", state="active",font=("微软雅黑", 12, "bold"),command=self.select_time)
        self.next.place(relx=0.5, rely=0.8,relwidth=0.2,relheight=0.1)
        self.next.configure(state="disabled")
        self.file_list = set()
        self.file_pid = set()

    def on_closing(self):
        try:
            st = subprocess.STARTUPINFO
            st.dwFlags = subprocess.STARTF_USESHOWWINDOW
            st.wShowWindow = subprocess.SW_HIDE
            for file_pid in self.file_pid:
                subprocess.Popen('taskkill /t /f /pid {}'.format(file_pid.pid), startupinfo=st, shell=False)
        except:
            pass
        self.destroy()

    def select_file(self):
        filenames = filedialog.askopenfilenames()
        self.label_show = tk.Label(self.basic_frame, text="已选择文件:", bg="#800080", font=("微软雅黑", 18, "bold"))
        for file in filenames:
            self.file_list.add(file)
        self.file_id = 1
        if len(self.file_list) > 0:
            for file in self.file_list:
                self.file_id += 1
                rely = float("0.{}".format(self.file_id))
                if self.file_id == 7:
                    tk.Label(self.basic_frame, text="..................", bg="#800080", font=("微软雅黑", 18, "bold")).place(relx=0.1,
                                                                                                         rely=rely,
                                                                                                         relwidth=0.8,
                                                                                                         relheight=0.1)
                    break
                if len(file)<=30:
                    show_text = file
                else:
                    show_text = "........." + file[-30:]
                tk.Label(self.basic_frame, text=show_text, bg="#800080", font=("微软雅黑", 12, "bold")).place(relx=0.1, rely=rely, relwidth=0.8, relheight=0.1)
            self.label_show.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.1)
            self.next.configure(state="active")
            self.select_file_button.place_forget()
            self.cancel = tk.Button(self.basic_frame, text="取消", bg="red", state="active",font=("微软雅黑", 12, "bold"),command=self.go_back)
            self.cancel.place(relx=0.2, rely=0.8, relwidth=0.2, relheight=0.1)
            self.show_info_label.place_forget()

    def select_time(self):
        # 清空所有显示
        for k, v in self.basic_frame.children.items():
            v.place_forget()
        self.time_every = tk.Label(self.basic_frame, text="每天", bg="#800080",font=("微软雅黑", 20, "bold"))
        self.time_every.place(relx=0.2, rely=0.1, relwidth=0.2, relheight=0.3)
        # 开始时间
        self.timevariable = tk.StringVar()
        self.timevariable.set("请选择开始时间")
        self.start_time_com = ttk.Combobox(self.basic_frame,textvariable=self.timevariable)
        self.start_time_com["value"] = ("18:30","19:30","20:30")
        self.start_time_com.place(relx=0.3, rely=0.4, relwidth=0.3, relheight=0.1)
        # 循环次数
        self.timesvar = tk.StringVar()
        self.timesvar.set("请选择循环次数")
        self.times_com = ttk.Combobox(self.basic_frame, textvariable=self.timesvar)
        self.times_com["value"] = ("1", "2", "3","4","5","6","7","8","9","10")
        self.times_com.place(relx=0.3, rely=0.5, relwidth=0.3, relheight=0.1)
        # 开始
        self.start = tk.Button(self.basic_frame, text="start", bg="red", state="active",font=("微软雅黑", 12, "bold"),command=self.run)
        self.start.place(relx=0.5, rely=0.8, relwidth=0.2, relheight=0.1)
        self.cancel.place(relx=0.2, rely=0.8, relwidth=0.2, relheight=0.1)

        # 参数提示信息
        self.varable_show = tk.Label(self.basic_frame, text="输入的参数有误，\n请检查...", bg="#800080", fg="red",font=("微软雅黑", 15, "bold"))

    def run(self):
        self.time_var = self.timevariable.get()
        self.times_var = self.timesvar.get()
        bool = (self.time_var in ("18:30","19:30","20:30") and self.times_var in (str(i) for i in range(1,11)))
        if bool:
            self.varable_show.place_forget()
            tt = threading.Thread(target=self.run_process)
            tt.setDaemon(True)
            tt.start()
            self.show_status()
        else:
            self.varable_show.place(relx=0.6, rely=0.35, relwidth=0.5, relheight=0.3)

    def run_process(self):
        expect_hour,expect_min = self.time_var.split(":")
        expect_hour_int = int(expect_hour)
        expect_min_int = int(expect_min)
        status = True
        # 记录明天凌晨时间
        tomorrow_time_stamp = None
        while True:
            times = int(self.times_var)
            if status:
                time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                hour, min, _ = time_str.split()[1].split(":")
                hour_int = int(hour)
                min_int = int(min)
                _bool = (hour_int > expect_hour_int) or (hour_int == expect_hour_int and min_int >= expect_min_int)
                if _bool:
                    today = datetime.datetime.now()
                    offset = datetime.timedelta(days=1)
                    tomorrow_time = (today + offset).strftime("%Y-%m-%d 00:00:01")
                    tomorrow_time_strptime = time.strptime(tomorrow_time, '%Y-%m-%d %H:%M:%S')
                    tomorrow_time_stamp = time.mktime(tomorrow_time_strptime)
                    while times:
                        print("times...")
                        tt = threading.Thread(target=self.run_file)
                        tt.setDaemon(True)
                        tt.start()
                        tt.join()
                        times -= 1
                        time.sleep(1800)
                    status = False
            else:
                if time.time() >= tomorrow_time_stamp:
                    status = True
            time.sleep(1)

    def run_file(self):
        ts = []
        for file in self.file_list:
            t = threading.Thread(target=self.start_task, args=(file,))
            ts.append(t)
        for h in ts:
            h.setDaemon(True)
        for i in ts:
            i.start()
        for j in ts:
            j.join()


    def start_task(self,file):
        st = subprocess.STARTUPINFO
        st.dwFlags = subprocess.STARTF_USESHOWWINDOW
        st.wShowWindow = subprocess.SW_HIDE
        file_pid = subprocess.Popen(r"{}".format(file), startupinfo=st, shell=True)
        self.file_pid.add(file_pid)
        file_pid.wait()

    def show_status(self):
        text = """
    任务设置成功
    将在每天的{timevar}点后
    进行{timesvar}次测试
        """.format(timevar=self.time_var,timesvar=self.times_var)
        for _,v in self.basic_frame.children.items():
            v.place_forget()
        tk.Label(self.basic_frame, text=text, bg="#800080", fg="green",font=("微软雅黑", 30, "bold")).place(relx=0.05, rely=0.2, relwidth=0.9, relheight=0.3)
        self.time_label = tk.Label(self.basic_frame, text="", bg="#800080", fg="green", font=("微软雅黑", 15, "bold"))
        self.time_label.place(relx=0.1,rely=0.5,relwidth=0.8,relheight=0.5)
        self.show_time()

    def show_time(self):
        time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        time_str = "当前时间: {timestr}".format(timestr=time_str)
        self.time_label.configure(text=time_str)
        self.after(1000,self.show_time)


    def go_back(self):
        self.file_list.clear()
        for k,v in self.basic_frame.children.items():
            v.place_forget()
        self.next.configure(state="disabled")
        self.cancel.place_forget()
        self.select_file_button.place(relx=0.3, rely=0.5, relheight=0.1, relwidth=0.5)
        self.label_show.place_forget()
        # 下一步
        self.next.place(relx=0.5, rely=0.8, relwidth=0.2, relheight=0.1)
        # 温馨提示
        self.show_info_label.place(relx=0.1, rely=0.3, relheight=0.1, relwidth=0.8)

    def start(self):
        self.mainloop()


if __name__ == '__main__':
    import os
    multiprocessing.freeze_support()
    case_task = TkBasic()
    case_task.start()

